package pkg

import (
	"common/initialize"
	"fmt"
	"github.com/smartwalle/alipay/v3"
)

type Payment interface {
	Pay(Subject, OutTradeNo, TotalAmount string) string
}

type Alipay struct {
	AppId      string
	PrivateKey string
	NotifyURL  string
	ReturnURL  string
}

func NewPay() *Alipay {
	cf := initialize.Config.Alipay
	return &Alipay{
		AppId:      cf.AppId,
		PrivateKey: cf.PrivateKey,
		NotifyURL:  cf.NotifyURL,
		ReturnURL:  cf.ReturnURL,
	}
}

func (a *Alipay) Pay(Subject, OutTradeNo, TotalAmount string) (string, error) {
	var privateKey = a.PrivateKey // 必须，上一步中使用 RSA签名验签工具 生成的私钥
	var client, err = alipay.New(a.AppId, privateKey, false)
	if err != nil {
		return "", err
	}
	var p = alipay.TradeWapPay{}
	p.NotifyURL = a.NotifyURL
	p.ReturnURL = a.ReturnURL
	p.Subject = Subject
	p.OutTradeNo = OutTradeNo
	p.TotalAmount = TotalAmount
	p.ProductCode = "QUICK_WAP_WAY"
	fmt.Println(a.NotifyURL)
	url, err := client.TradeWapPay(p)
	if err != nil {
		return "", err
	}
	var payURL = url.String()
	return payURL, nil
}
